package com.yige.web.timer

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.DateUtil
import com.yige.common.SystemConstant
import com.yige.service.mongoService.MongoAccountsService
import com.yige.service.mongoService.MongoIncomeService
import com.yige.service.mongoService.MongoStudentService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

/**
 * Created by sunhao on 2015/11/17 0017.
 */

@Component
class AccountsTimer {

    @Autowired
    MongoAccountsService accountsService

    @Autowired
    MongoIncomeService incomeService

    @Autowired
    MongoStudentService studentService


    synchronized execute() {
        println("timerStart:" + DateUtil.formatDatetime(new Date(System.currentTimeMillis())))
        def studentList = studentService.findNoPayStudent(), studentFinish = studentService.findFinishStudent(), incomeList = incomeService.findNoPayStudent()
        DBObject student_db, accounts
        double money
        boolean flag
        def str = new StringBuffer()
        accountsService.removeCollection()
        studentList.each {
            student_db = studentService.findOneById(it._id)
            money = it.n * it.price * -1
            str.append("你预交的").append(it.name).append("课费已经到期，并已经超出").append(Integer.toString(-1 * it.get("n"))).append("节课程,已欠费").append(Double.toString(money)).append("元，，请及时缴费")
            accounts = [_id: UUID.randomUUID().toString(), student: student_db.name, date: new Date(System.currentTimeMillis()), action: str.toString(), status: SystemConstant.INCOME_NOPAY, lesson: it.lesson] as BasicDBObject
            str = new StringBuffer()
            flag = accountsService.insertOne(accounts)
        }
        studentFinish.each {
            student_db = studentService.findOneById(it._id)
            money = it.n * it.price * -1
            str.append("你预交的").append(it.name).append("课费已经到期，或新报名的").append(it.name).append("课费还未交费，请及时缴费")
            accounts = [_id: UUID.randomUUID().toString(), student: student_db.name, date: new Date(System.currentTimeMillis()), action: str.toString(), status: SystemConstant.INCOME_NOPAY, lesson: it.lesson] as BasicDBObject
            str = new StringBuffer()
            flag = accountsService.insertOne(accounts)
        }
        incomeList.each {
            student_db = studentService.findOneById(it.student)
            str.append("收据：").append(Integer.toString(it.get("num"))).append(",未交款").append(Double.toString(it.get("total"))).append("元，请及时缴费")
            accounts = [_id: UUID.randomUUID().toString(), student: student_db.name, date: it.date, action: str.toString(), status: SystemConstant.INCOME_NOPAY, income: it._id] as BasicDBObject
            str = new StringBuffer()
            flag = accountsService.insertOne(accounts)
        }
        println("timerOver:" + DateUtil.formatDatetime(new Date(System.currentTimeMillis())))
    }

}
